package com.michael.leetcode;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class GetFolderNames_1487 {

    public String[] getFolderNames(String[] names) {
        String[] res = new String[names.length];
        Map<String, Integer> map = new HashMap<>();
        int l = names.length;
        for(int i = 0; i < l; i++) {
            String s = names[i];
            if (!map.containsKey(s)){
                res[i] = s;
                map.put(s,1);
            }else {
                int k = map.get(s);
                while (map.containsKey(s+"("+k+")")){
                    k++;
                }
                res[i] = s+"("+k+")";
                map.put(s, k+1);
                map.put(res[i], 1);
            }
        }

        return res;
    }


    public String[] getFolderNames1(String[] names) {
        String[] res = new String[names.length];
        Map<String, Integer> map = new HashMap<>();

        for(int i = 0; i < names.length; i++) {
            if (!map.containsKey(names[i])){
                res[i] = names[i];
            }else {
                res[i] = find(names[i], map);
            }
            map.put(res[i],map.getOrDefault(res[i],0)+1);

        }

        return res;
    }



    public String find(String name, Map<String, Integer> map){
        if (!map.containsKey(name)){
            return name;
        }else {
            String key;
            if (name.indexOf('(')> 0){
                int c = Integer.parseInt(name.substring(name.indexOf('(')+1, name.indexOf(')'))) + 1;
                key = name.substring(0, name.indexOf('(')) + "(" + c + ")";
            }else {
                key = name+"("+map.get(name)+")";
            }
            return find(key, map);
        }
    }

    @Test
    public void test(){
        String[] names = {"kaido","kaido(1)","kaido","kaido(1)"};
        getFolderNames(names);
    }
}